package koscom.corebase.nam;
import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Image;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.nio.ByteBuffer;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.Locale;

import javax.swing.BorderFactory;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;
import javax.swing.UIDefaults;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;

import org.jdesktop.swingx.JXDatePicker;


@SuppressWarnings("serial")
public class A2004 extends JFrame {

	private JPanel contentPane;
	private JTextField txtAccountNumber;
	private JTextField txtAccountOwner;
	private JTable tblAccident;
	private JTextField txtResult;
	private JTextField txtBranchNumber;
	private JTextField txtBranchName;
	private DefaultTableModel mdlAccident;
	public SClient client;
	
	public String sendString = new String();
	JXDatePicker DateFrom;
	JXDatePicker DateTo;
	JComboBox cmbInquiryType;
	JComboBox cmbAccountType;
	JComboBox cmbAccidentType;
	JComboBox cmbAccdientRegistType;
	
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		//기본 폰트 설정
		try {
			UIDefaults swingComponentDefaultTable = UIManager.getDefaults();
			Enumeration<Object> allDefaultKey = swingComponentDefaultTable.keys();
			while(allDefaultKey.hasMoreElements()) {
				String defaultKey = allDefaultKey.nextElement().toString();
				if(defaultKey.indexOf("font") != -1) {
					Font newDefaultFont = new Font("맑은 고딕", Font.PLAIN, 12);
					//System.out.println(defaultKey);
					UIManager.put(defaultKey, newDefaultFont);
				}
			}
		UIManager.getDefaults().put("Button.margin", new Insets(0,0,0,0));
		
		} catch (Exception e) {
			e.printStackTrace();
		}	
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					A2004 frame = new A2004();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
	
	public void checkDate(int type)
	{
		if(type==1)//DateTo
		{
			Date d = DateTo.getDate();
			if(d==null) System.out.println("널");
			else System.out.println(d.toString());
		}
		else if(type==2)//DateFrom
		{
			
		}
	}
	/**
	 * Create the frame.
	 */
	/*
	this.getInputMap( ).put( KeyStroke.getKeyStroke( '\n' ), "transferFokus" );
  	this.getActionMap( ).put( "transferFokus", transferFokusa );
	*/
	public A2004() {
		client = new SClient(null, 0, false);
		
		client.setListener(new SClient.OnListener() {
			@Override
			public void onRcvData(ByteBuffer rcvBuff) {
				try {
					byte[] trid = new byte[6];
					rcvBuff.get(trid, 0, trid.length);
					String trString = new String(trid, "UTF-8");
					
					if(trString.equals("2222OO"))
					{
						System.out.println("2222OO");
						byte[] bytes = new byte[rcvBuff.remaining()];
						rcvBuff.get(bytes);
						String rString = new String(bytes, "UTF-8");
						txtAccountOwner.setText(rString.substring(0,20).trim());
					}
					else if(trString.equals("2222XX"))
					{
						System.out.println("2222XX");
						txtResult.setText("해당 계좌가 존재하지 않습니다");
						//setEmpty(allComponents);
					}
					else if(trString.equals("20049D"))
					{
						txtResult.setText("내역 조회가 완료되었습니다");
					}
					else if(trString.equals("20049A"))
					{
						String[] slRow = new String[5];
						//acc_num
						byte[] readByte = new byte[11];
						rcvBuff.get(readByte, 0, 11);
						String slAccnum = new String(readByte, "UTF-8").trim(); 
						
						//ar_check
						readByte = new byte[4];
						rcvBuff.get(readByte, 0, 4);
						String slArcheck = new String(readByte, "UTF-8").trim();
						
						//ar_date
						readByte = new byte[20];
						rcvBuff.get(readByte, 0, 19);
						String slArDate = new String(readByte, "UTF-8").trim(); 
						
						//ar_cancle_date
						readByte = new byte[20];
						rcvBuff.get(readByte, 0, 19);
						String slArCancelDate = new String(readByte, "UTF-8").trim();
						
						String slAccType = "종합계좌";
						if(slAccnum.substring(3,5).equals("01"))
							slAccType = "위탁계좌";
						else if(slAccnum.substring(3, 5).equals("51"))
							slAccType = "선물계좌";
						
						String arType = "등록";
						slRow[0] = slAccType;
						slRow[1] = slAccnum;
						slRow[2] = "압류(전거래정지)";
						slRow[3] = slArDate;
						slRow[4] = arType;
						if(cmbAccdientRegistType.getSelectedIndex()!=1)
							mdlAccident.addRow(slRow);
						if(slArcheck.equals("XXXX") && cmbAccdientRegistType.getSelectedIndex()!=0)
						{
							arType = "해지";
							slRow[3] = slArCancelDate;
							slRow[4] = arType;
							mdlAccident.addRow(slRow);
						}
							
					}
					else if(trString.equals("20049S"))
					{
						String[] slRow = new String[5];
						//acc_num
						byte[] readByte = new byte[11];
						rcvBuff.get(readByte, 0, 11);
						String slAccnum = new String(readByte, "UTF-8").trim(); 
						
						//sg_date
						readByte = new byte[20];
						rcvBuff.get(readByte, 0, 19);
						String slSgDate = new String(readByte, "UTF-8").trim();
						
						//sg_check
						readByte = new byte[4];
						rcvBuff.get(readByte, 0, 4);
						String slSgCheck = new String(readByte, "UTF-8").trim();
						String slSgCheckString = "해지";
						if(slSgCheck.subSequence(0, 2).equals("11"))
						{
							slSgCheckString = "등록";
						}
						//sg_type
						readByte = new byte[4];
						rcvBuff.get(readByte, 0, 4);
						String slSgType = new String(readByte, "UTF-8").trim();
						
						String slAccType = "종합계좌";
						if(slAccnum.substring(3,5).equals("01"))
							slAccType = "위탁계좌";
						else if(slAccnum.substring(3, 5).equals("51"))
							slAccType = "선물계좌";
						
						String slSgTypeString = null;
						if(slSgType.equals("0001"))
						{
							slSgTypeString = "현물거래정지";
						}
						else if(slSgType.equals("0002"))
						{
							slSgTypeString = "전거래정지";
						}
						else if(slSgType.equals("0003"))
						{
							slSgTypeString = "불공정거래";
						}
						else if(slSgType.equals("0000"))
						{
							slSgTypeString = "출금고정지";
						}
						// cancel date
						readByte = new byte[20];
						rcvBuff.get(readByte, 0, 19);
						String slCancelDate = new String(readByte, "UTF-8").trim();
						
						slRow[0] = slAccType;
						slRow[1] = slAccnum;
						slRow[2] = slSgTypeString;
						slRow[3] = slSgDate;
						slRow[4] = slSgCheckString;
						
						if(cmbAccdientRegistType.getSelectedIndex()!=1)
							mdlAccident.addRow(slRow);
						if(slSgCheck.subSequence(2, 4).equals("22") && cmbAccdientRegistType.getSelectedIndex()!=0)
						{
							String[] slCancelRow = new String[5];
							slCancelRow[4] = new String("해지");
							slCancelRow[0] = slAccType;
							slCancelRow[1] = slAccnum;
							slCancelRow[2] = slSgTypeString;
							slCancelRow[3] = slCancelDate;
							mdlAccident.addRow(slCancelRow);
						}						
					}
				}
				catch(Exception rcvex){}
			}
		});
		
		/**
		 * DatePicker Initialize
		 */
		DateFrom = new JXDatePicker();
		DateFrom.getEditor().setEditable(false);
		
		PropertyChangeListener listener = new PropertyChangeListener() {
			public void propertyChange(PropertyChangeEvent e) {
				if ("date".equals(e.getPropertyName())) {
					Date fr = DateFrom.getDate();
					Date to = DateTo.getDate();
					if(fr==null || to==null) ;
					else if(to.before(fr)) DateTo.setDate(fr);
				}
			}
		};
		DateTo = new JXDatePicker();
		DateFrom.addPropertyChangeListener(listener);
		DateTo.addPropertyChangeListener(listener);
		
		DateTo.getEditor().setEditable(false);
		SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd", Locale.KOREA);
		DateFrom.setFormats(format);
		DateTo.setFormats(format);
		JButton btnDateTo = (JButton)DateTo.getComponent(1);
		
		ImageIcon lg = new ImageIcon("img\\cal2.png");//endar.PNG");
		Image lgImage = lg.getImage();  
		ImageIcon loginImage = new ImageIcon(lgImage.getScaledInstance(20, 20, java.awt.Image.SCALE_SMOOTH));
		
		btnDateTo.setIcon(loginImage);
		btnDateTo.setBorder(BorderFactory.createEmptyBorder());
		
		JButton btnDateFrom = (JButton)DateFrom.getComponent(1);
		btnDateFrom.setIcon(loginImage);
		btnDateFrom.setBorder(BorderFactory.createEmptyBorder());
		
		Date now = new Date();
		DateTo.setDate(now);
		DateFrom.setDate(now);
		// date set.
		
		setTitle("CoreBASE [2004] 계좌사고등록및해지내역");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 849, 465);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		DateFrom.setBounds(114, 57, 116, 21);
		DateTo.setBounds(250, 57, 116, 21);
		contentPane.add(DateFrom);
		contentPane.add(DateTo);
		
		JLabel lblInType = new JLabel("조회구분");
		lblInType.setBounds(22, 10, 80, 15);
		contentPane.add(lblInType);
		
		JLabel lblAccountNumber = new JLabel("계좌번호");
		lblAccountNumber.setBounds(388, 10, 90, 15);
		contentPane.add(lblAccountNumber);
		
		JLabel lblBranchNumber = new JLabel("지점번호");
		lblBranchNumber.setBounds(22, 35, 80, 15);
		contentPane.add(lblBranchNumber);
		
		txtAccountNumber = new JTextField();
		txtAccountNumber.addKeyListener(new KeyAdapter() {
			@Override
			public void keyReleased(KeyEvent e) {
				if(e.getKeyChar() == KeyEvent.VK_ENTER)
				{
					if(txtAccountNumber.getText().length()==11)
					{
						txtResult.setText("계좌번호 조회...");
						sendString = "2222ID"+String.format("%11s", txtAccountNumber.getText());
						System.out.println(sendString);
						client.writeString(sendString);
					}
					else
					{
						txtResult.setText("계좌번호 입력 오류");
					}
				}
			}
		});
		txtAccountNumber.setBounds(490, 7, 116, 21);
		contentPane.add(txtAccountNumber);
		txtAccountNumber.setColumns(10);
		
		txtAccountOwner = new JTextField();
		txtAccountOwner.setEditable(false);
		txtAccountOwner.setBounds(618, 7, 116, 21);
		contentPane.add(txtAccountOwner);
		txtAccountOwner.setColumns(10);
		
		JButton btnSubmit = new JButton("전송");
		btnSubmit.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				mdlAccident.setRowCount(0);
				ByteBuffer sendBuffer = ByteBuffer.allocateDirect(1024);
				sendBuffer.clear();
				
				sendBuffer.position(0);
				sendBuffer.limit(6);
				sendBuffer.put("200499".getBytes());
				
				sendBuffer.position(sendBuffer.limit());
				sendBuffer.limit(sendBuffer.limit()+4);
				sendBuffer.put(String.format("%04d", cmbInquiryType.getSelectedIndex()).getBytes());
				
				sendBuffer.position(sendBuffer.limit());
				sendBuffer.limit(sendBuffer.limit()+11);
				sendBuffer.put(txtAccountNumber.getText().getBytes());
				
				sendBuffer.position(sendBuffer.limit());
				sendBuffer.limit(sendBuffer.limit()+4);
				sendBuffer.put(String.format("%04d", cmbAccountType.getSelectedIndex()).getBytes());
				
				sendBuffer.position(sendBuffer.limit());
				sendBuffer.limit(sendBuffer.limit()+4);
				sendBuffer.put(String.format("%04d", cmbAccdientRegistType.getSelectedIndex()).getBytes());
				
				sendBuffer.position(sendBuffer.limit());
				sendBuffer.limit(sendBuffer.limit()+20);
				sendBuffer.put(DateFrom.getEditor().getText().getBytes());
				
				sendBuffer.position(sendBuffer.limit());
				sendBuffer.limit(sendBuffer.limit()+20);
				sendBuffer.put(DateTo.getEditor().getText().getBytes());
				
				sendBuffer.position(sendBuffer.limit());
				sendBuffer.limit(sendBuffer.limit()+4);
				sendBuffer.put(String.format("%04d", cmbAccidentType.getSelectedIndex()).getBytes());
				
				sendBuffer.limit(1024);
				sendBuffer.rewind();
				client.writeBuffer(sendBuffer);
				sendBuffer.clear();
//				TRID	6	6
//				조회구분	4	10
//				계좌번호	11	21
//				상품유형	4	25
//				사고등록구분	4	29
//				조회일자	50	79
//				사고유형	20	99
				client.writeString(sendString);
				sendString="";
				txtResult.setText("조회가 완료 되었습니다");
			}
		});
		btnSubmit.setBounds(732, 81, 97, 23);
		contentPane.add(btnSubmit);
		
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
		scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
		scrollPane.setBounds(12, 114, 820, 275);
		contentPane.add(scrollPane);
		
		mdlAccident = new DefaultTableModel(null, 
			new String[] {
				"계좌유형", "계좌번호", "사고유형", "사고등록일", "등록구분"
			});
//		{
//			public Class<String> getColumnClass(int column) {
//                return String.class;
//            }
//		};
       
		tblAccident = new JTable(mdlAccident){
			@Override
			public boolean isCellEditable(int row, int column) {
				return false;
			}
		};
		tblAccident.setEnabled(false);
		tblAccident.getTableHeader().setReorderingAllowed(false);
		tblAccident.getTableHeader().setResizingAllowed(false);
//		tblAccident.setAutoCreateRowSorter(true);
		//TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(tblAccident.getModel());
		//tblAccident.setRowSorter(sorter);
		//테이블 순서변경금지, 리사이징 금지, 한줄만 선택 가능, 편집금지, 소트
		
		scrollPane.setViewportView(tblAccident);
		
		txtResult = new JTextField();
		txtResult.setFont(new Font("맑은 고딕", Font.BOLD, 12));
		txtResult.setForeground(Color.RED);
		txtResult.setEditable(false);
		txtResult.setBounds(9, 399, 820, 21);
		contentPane.add(txtResult);
		txtResult.setColumns(10);
		
		cmbInquiryType = new JComboBox();
		cmbInquiryType.setModel(new DefaultComboBoxModel(new String[] {"지점별", "계좌별"}));
		cmbInquiryType.setBounds(114, 7, 116, 23);
		contentPane.add(cmbInquiryType);
		
		txtBranchNumber = new JTextField();
		txtBranchNumber.setText("001");
		txtBranchNumber.setBounds(114, 35, 40, 18);
		contentPane.add(txtBranchNumber);
		
		JLabel lblAccType = new JLabel("상품유형");
		lblAccType.setBounds(388, 35, 90, 15);
		contentPane.add(lblAccType);
		
		JLabel lblInDate = new JLabel("조회일자");
		lblInDate.setBounds(22, 60, 80, 15);
		contentPane.add(lblInDate);
		
		JLabel lblAccidentType = new JLabel("사고유형");
		lblAccidentType.setBounds(22, 85, 80, 15);
		contentPane.add(lblAccidentType);
		
		JLabel lblAccidentRegistType = new JLabel("사고등록구분");
		lblAccidentRegistType.setBounds(388, 60, 90, 15);
		contentPane.add(lblAccidentRegistType);
		
		cmbAccountType = new JComboBox();
		cmbAccountType.setModel(new DefaultComboBoxModel(new String[] {"0. 종합", "1. 위탁", "2. 선물옵션", "3. 전체"}));
		cmbAccountType.setBounds(490, 31, 90, 23);
		cmbAccountType.setSelectedIndex(3);
		contentPane.add(cmbAccountType);
		
		cmbAccdientRegistType = new JComboBox();
		cmbAccdientRegistType.setModel(new DefaultComboBoxModel(new String[] {"1. 등록", "2. 해지", "3. 전체"}));
		cmbAccdientRegistType.setBounds(490, 57, 90, 23);
		cmbAccdientRegistType.setSelectedIndex(2);
		contentPane.add(cmbAccdientRegistType);
		
		txtBranchName = new JTextField();
		txtBranchName.setText("CB영업부");
		txtBranchName.setEditable(false);
		txtBranchName.setBounds(166, 33, 116, 21);
		contentPane.add(txtBranchName);
		txtBranchName.setColumns(10);
		
		JLabel lblST = new JLabel("~");
		lblST.setBounds(235, 60, 9, 15);
		contentPane.add(lblST);
		
		cmbAccidentType = new JComboBox();
		cmbAccidentType.setModel(new DefaultComboBoxModel(new String[] {"출금고정지", "현물거래정지", "전거래정지", "불공정거래", "압류(전거래정지)", "전체"}));
		cmbAccidentType.setBounds(114, 81, 192, 23);
		cmbAccidentType.setSelectedItem("전체");
		contentPane.add(cmbAccidentType);
		
		TableCellRenderer ren = new TableColor();
		
		try {
			tblAccident.setDefaultRenderer(Class.forName("java.lang.Object"), ren);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		
		
	}
	
	public class TableColor extends DefaultTableCellRenderer {

		public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {

			Component cell = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

			// 가운데 정렬
			this.setHorizontalAlignment(JLabel.CENTER);

			// 색 삽입
			if ((row%2)==1) {
				cell.setBackground(new Color(195, 217, 235));
			} else {
				cell.setBackground(Color.WHITE);
			}

			return cell;

		}

	}
	
}
